<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.palyStatus" class="filter-item" placeholder="状态" :clearable="true">
        <el-option value="0" label="正常" />
        <el-option value="1" label="停用" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" align="center" width="100">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="播放名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.playName }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="投放位置" align="center">-->
      <!--<template slot-scope="{row}">-->
      <!--<span>{{ row.playName }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.playStatus }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="制作人">-->
      <!--<template slot-scope="{row}">-->
      <!--<span>{{ row.userType }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">

          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <el-row>
          <el-col>
            <el-form-item label="标题" prop="title">
              <el-input v-model="temp.playName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="简介" prop="title">
              <el-input
                v-model="temp.playDesc"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="推送频率" prop="title">
              <el-select v-model="temp.frequency" class="filter-item" placeholder="请选择">
                <el-option :value="1" label="每天1次" />
                <el-option :value="2" label="每天2次" />
                <el-option :value="3" label="每天3次" />
                <el-option :value="4" label="每天4次" />
                <el-option :value="5" label="每天5次" />
                <el-option :value="6" label="每天6次" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="title">
              <el-select v-model="temp.playStatus" class="filter-item" placeholder="请选择">
                <el-option value="0" label="正常" />
                <el-option value="1" label="停用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="获取资源" prop="title">
              <el-select
                v-model="temp.resourceIdList"
                multiple
                collapse-tags
                placeholder="请选择"
              >
                <el-option
                  v-for="item in resourcelist"
                  :key="item.value"
                  :label="item.resourceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="投放位置" prop="title">
              <el-tree
                ref="treeTable"
                :data="dataList"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false"
                show-checkbox
              >
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <span>{{ data.lable }}</span>
                </span>
              </el-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <!-- <el-button @click="getCheckedNodes">
          通过 node 获取
        </el-button> -->
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { pageQuareApi, getOptionalResource, editApi, addApi, getByIdApi, DeleteApi, getQuestionFromPaper, getOrgTree } from '@/api/sysmanage'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// import draggable from 'vuedraggable'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'Opsurvey',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      /* eslint-disable */
      tableKey: 0,
      list: [],
      resourcelist:[],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
       palyStatus:''
      },
      temp:  {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      updateObj:{
        index:'',
        data:[]
      },

      // ------------------------------
      fileHeader:'',
      dataList:[],
    
    }
  },
  created() {
    this.handleFilter()
    let token=getToken('Admin-Token')
    this.fileHeader={
      token:token
    }
    
  },
  methods: {
    getList() {
      this.listLoading = true
      pageQuareApi(this.listQuery,'play').then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getResourceList(query) {
      // 获取所有资源
      this.listLoading = true
      if(!query){
         query=''
      }
      getOptionalResource (query).then(response => {
        console.log("TCL: getResourceList -> response", response)
        this.resourcelist = response.data
        // this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {//重置修改模态框
      this.temp = {
        "playName": "",
        "playDesc":'',
        "frequency":'',
        "playStatus": "",
        "playStatusDesc":'',
        "resourceIdList": [],
        "windowIdList": []
      }
      this.resourcelist =[]//清空资源列表
    },
    handleCreate() {
      this.resetTemp()
      this.getResourceList()
      getOptionalResource ({}).then(response => {
        console.log("TCL: getResourceList -> response", response)
        this.resourcelist = response.data
      })
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // 获取树状列表
      getOrgTree().then(response => {
      const { data } = response
      this.dataList = data
      console.log('TCL: getData -> this.dataList', this.dataList)
      setTimeout(() => {
        this.listLoading = false
      }, 1.5 * 1000)
    })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
          let treeList=this.$refs.treeTable.getCheckedNodes()
          this.temp.windowIdList=treeList.map(ele=>{
            return ele.id
          })
          addApi(this.temp,'play').then((res) => {
            const{code,message,data}=res
            if(code==='200'){
              this.$message({
                message: message,
                type: 'success',
              })
               this.dialogFormVisible = false
               this.list.unshift(data)
            }else{
              this.$message({
                message: message,
                type: 'warning',
              })
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
         let treeList=this.$refs.treeTable.getCheckedNodes()
          this.temp.windowIdList=treeList.map(ele=>{
            return ele.id
          })
          console.log("TCL: updateData ->  this.temp.resourceIdList",  this.temp.resourceIdList)
          editApi(this.temp,'play').then((res) => {
            this.dialogFormVisible = false
            if(res.code==='200'){
               this.$message({
                message: res.message,
                type: 'success',
              })
             
              const row=Object.assign(data, this.temp)
              this.list.splice(index,1,row)
            }else{
               this.$message({
                message: res.message||'修改失败',
                type: 'error'
              })
            }
           
          })
        }
      })
    },
    handleUpdate(row,index) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      let {id}=row
      getByIdApi({id},'play').then(res=>{
        let _this=this
        const { code, data, message } = res
        if (code === '200') {
          this.$message({
            message: message,
            type: 'success'
          })
          // this.temp=data
          let {resourceList,windowSelectTree,windowIdList,playName,playDesc,frequency,playStatus,playStatusDesc,id}=data

          this.temp = {
            "id":id,
            "playName": playName,
            "playDesc":playDesc,
            "frequency":frequency,
            "playStatus": playStatus,
            "playStatusDesc":playStatusDesc,
            "resourceIdList": [],
            "windowIdList": windowIdList
          }
          resourceList=resourceList||[]
          resourceList.forEach(ele=>{
            if(ele.id){
              this.temp.resourceIdList.push(ele.id)
            }
          })
          console.log("TCL: handleUpdate ->  this.resourceIdList",  this.temp.resourceIdList)
          this.dataList=windowSelectTree
          this.$refs.treeTable.setCheckedKeys(windowIdList);
        } else {
          this.$message({
            message: message,
            type: 'warning'
          })
        }
        
      })
      this.getResourceList({id})
    },
    handleDelete(row,index) {
      this.$confirm('此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
         DeleteApi({id:row.id},'play').then(res=>{
             this.$message({
                message: res.message,
                type: 'success'
              })
              this.list.splice(index,1)
          }).catch(err=>{
             this.$message({
                message:err.message,
                type: 'error'
              })
          })
       
        // row.status = status
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    // 获取树型结构列表选中的数组
    getCheckedNodes(){
      let a=this.$refs.treeTable.getCheckedNodes()
      console.log("TCL: getCheckedNodes -> a", a)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    
   
  }
}
</script>
